﻿#include "widget.h"
#include "ui_widget.h"
#include "utils.h"
#include <QMessageBox>
#include <QDebug>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    , emqx(new EmqxController(this))
{
    ui->setupUi(this);

    // 连接信号
    connect(emqx, &EmqxController::outputReceived, this, &Widget::handleOutput);
    connect(emqx, &EmqxController::errorReceived, this, &Widget::handleError);
    connect(emqx, &EmqxController::statusChanged, this, &Widget::handleStatusChanged);

    // 恢复开机自启状态
    //ui->autoStartCheckBox->setChecked(Utils::isAutoStart());

    // 初始刷新状态
    on_btnRefresh_clicked();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_btnStart_clicked()
{
    if (emqx->start()) {
       // ui->statusLabel->setText("状态：正在启动...");
    } else {
        QMessageBox::warning(this,  "错误",  "启动失败，请查看日志");
    }
}

void Widget::on_btnStop_clicked()
{
    if (emqx->stop()) {
        ui->statusLabel->setText( "状态：已停止");
    } else {
        QMessageBox::warning(this,  "错误",  "停止失败");
    }
}

void Widget::on_btnRestart_clicked()
{
    emqx->restart();
}

void Widget::on_btnInstall_clicked()
{
    if (emqx->install()) {
        QMessageBox::information(this,  "成功",  "服务安装成功");
    } else {
        QMessageBox::warning(this,  "失败",  "安装失败");
    }
}

void Widget::on_btnUninstall_clicked()
{
    if (emqx->uninstall()) {
        QMessageBox::information(this,  "成功",  "服务卸载成功");
    } else {
        QMessageBox::warning(this,  "失败",  "卸载失败");
    }
}

void Widget::on_btnRefresh_clicked()
{
    emqx->getStatus();
}

void Widget::on_autoStartCheckBox_toggled(bool checked)
{
    Utils::setAutoStart(checked);
}

void Widget::handleOutput(const QString &output)
{
    ui->logTextEdit->append( "输出:\n" + output +  "\n");
}

void Widget::handleError(const QString &error)
{
    ui->logTextEdit->append( "<font color='red'>输出:\n" + error +  "</font>\n");
}

void Widget::handleStatusChanged(EmqxController::Status status)
{
    qDebug()<<"wodgeddddddddd"<<status;
    switch (status) {
    case EmqxController::Running:

        qDebug()<<"wodgeddddddddd"<<status;

        ui->statusLabel->setText( "staues：运行中 ✅");
        break;
    case EmqxController::Stopped:
        ui->statusLabel->setText( "状态：已停止 ❌");
        break;
    default:
        ui->statusLabel->setText( "状态：未知 ⚠️");
        break;
    }
}

